<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限修复测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 1000px;
            margin: 0 auto;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            background: #f5f5f5;
            border-radius: 5px;
            white-space: pre-wrap;
            font-size: 12px;
        }
        button {
            padding: 10px 20px;
            margin: 5px;
            cursor: pointer;
            font-size: 14px;
        }
        .success { color: green; }
        .error { color: red; }
        .info { color: blue; }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        input[type="text"] {
            width: 300px;
            padding: 8px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h1>🔧 客户权限修复验证</h1>

    <div class="test-section">
        <h2>步骤1：获取有效的Token</h2>
        <p>请先在前端登录系统，然后按F12打开浏览器开发者工具：</p>
        <ol>
            <li>在Console标签页执行：<code>localStorage.getItem('token')</code></li>
            <li>复制返回的token值</li>
        </ol>
    </div>

    <div class="test-section">
        <h2>步骤2：输入Token和客户ID</h2>
        <div>
            <label>Token:</label><br>
            <input type="text" id="tokenInput" placeholder="粘贴你的token..." style="width: 600px;">
        </div>
        <div>
            <label>客户ID:</label><br>
            <input type="text" id="customerIdInput" placeholder="例如：1671">
        </div>
    </div>

    <div class="test-section">
        <h2>步骤3：测试权限修复</h2>

        <button onclick="testNormalAccess()">测试1：正常访问（不带contract_workflow）</button>
        <button onclick="testWithContractWorkflow()">测试2：带contract_workflow参数访问</button>
        <button onclick="testListAccess()">测试3：访问客户列表</button>

        <div class="result" id="result">请先输入Token和客户ID，然后点击测试按钮...</div>
    </div>

    <div class="test-section">
        <h2>修复说明</h2>
        <div class="info">
            <h3>✅ 已修复的问题：</h3>
            <ol>
                <li><strong>admin_id字段为0</strong>：现在正确记录当前操作人ID</li>
                <li><strong>录入人权限缺失</strong>：现在启用了creator权限，录入人可以访问自己录入的数据</li>
            </ol>

            <h3>🔧 权限检查逻辑：</h3>
            <pre>
用户在访问客户详情时，系统会检查以下权限（满足任意一项即可）：
1. personal权限：数据属于当前用户（belong_uid = 当前用户ID）
2. department权限：数据属于当前用户部门（belong_did = 当前用户部门ID）
3. shared权限：数据被共享给当前用户（share_ids包含当前用户ID）
4. approval权限：当前用户是审批人（check_uids包含当前用户ID）
5. <strong style="color: green;">creator权限：当前用户是录入人（admin_id = 当前用户ID）</strong> ← 新增
            </pre>

            <h3>🎯 测试预期：</h3>
            <ul>
                <li>测试1应该返回<strong style="color: green;">200 OK</strong>，因为现在是录入人在访问自己录入的数据</li>
                <li>测试2也应该返回200 OK（备用方案，合同创建流程使用）</li>
                <li>如果仍返回403，说明权限配置有问题</li>
            </ul>
        </div>
    </div>

    <script>
        function getToken() {
            return document.getElementById('tokenInput').value.trim();
        }

        function getCustomerId() {
            return document.getElementById('customerIdInput').value.trim() || '1671';
        }

        async function testApi(url, description) {
            const token = getToken();
            const resultDiv = document.getElementById('result');

            if (!token) {
                resultDiv.innerHTML = '<span class="error">❌ 请先输入Token</span>';
                return;
            }

            resultDiv.textContent = `正在测试: ${description}\n请求URL: ${url}\n\n`;

            try {
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + token
                    }
                });

                const data = await response.json();

                resultDiv.textContent += `HTTP状态: ${response.status} ${response.statusText}\n`;
                resultDiv.textContent += `响应数据:\n${JSON.stringify(data, null, 2)}\n\n`;

                if (response.status === 200) {
                    resultDiv.innerHTML += '<span class="success">✅ 测试通过！权限修复成功。</span>\n';
                    if (data.code === 0) {
                        resultDiv.innerHTML += `<span class="success">✓ 获取到客户数据：${data.data?.name || 'N/A'}</span>\n`;
                    }
                } else if (response.status === 403) {
                    resultDiv.innerHTML += '<span class="error">❌ 返回403权限错误，权限修复未生效</span>\n';
                } else if (response.status === 401) {
                    resultDiv.innerHTML += '<span class="error">⚠️ 返回401未授权（Token无效或已过期）</span>\n';
                } else {
                    resultDiv.innerHTML += '<span class="error">❌ 测试失败</span>\n';
                }
            } catch (error) {
                resultDiv.textContent += `错误: ${error.message}\n`;
            }
        }

        function testNormalAccess() {
            const customerId = getCustomerId();
            const url = `http://127.0.0.1:8000/api/customer/customer/view?id=${customerId}`;
            testApi(url, '正常访问（不带contract_workflow参数）');
        }

        function testWithContractWorkflow() {
            const customerId = getCustomerId();
            const url = `http://127.0.0.1:8000/api/customer/customer/view?id=${customerId}&contract_workflow=1`;
            testApi(url, '带contract_workflow参数访问（备用方案）');
        }

        function testListAccess() {
            const url = `http://127.0.0.1:8000/api/customer/customer/list?page=1&limit=10`;
            testApi(url, '访问客户列表');
        }
    </script>
</body>
</html>
